package targetToOffer.eigthDay;

/**
 * @author Godc
 * @description
 */
public class ReverseWords {
    public static void main(String[] args) {
        ReverseWordsSolution s = new ReverseWordsSolution();
        String s1 = s.reverseWords("the sky is blue");
        System.out.println(s1);
    }
}
class ReverseWordsSolution {
    public String reverseWords(String s) {
        String trim = s.trim();
        if(trim.length()==0) return "";
        StringBuffer buffer = new StringBuffer();
        int i = trim.length()-1,j = i;
        while(i>=0){
            // 查找第一个空格
            while(i>=0&&s.charAt(i)!=' ') i--;
            buffer.append(s.substring(i + 1, j + 1) + " ");
            // 跳过单词间空格
            while(i>=0&&s.charAt(i)==' ') i--;
            j = i;
        }
        return buffer.toString().trim();
    }

    /**
     * 利用库函数
     * @param s
     * @return
     */
    public String reverseWords1(String s){
        String[] strings = s.trim().split(" ");
        StringBuffer buffer = new StringBuffer();
        for (int i = strings.length-1; i >=0 ; i--) {
            if(strings[i].equals("")) continue;
            buffer.append(strings[i]+" ");
        }
        return buffer.toString().trim();
    }

}